import { GameMode } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { POFMapLoader } from "../components/mapLoader";
import { PillarOfFortuneWatingRoom } from "../components/waitingRoom";
import { PillarOfFortuneModule } from "../module";
import { PillarOfFortuneWatingState } from "./waitingState";

export class PillarOfFortuneLoadingState extends PillarOfFortuneModule.State {
    override onEnter(): void {
        this.init();
        this.initPlayer();
        this.addComponent(POFMapLoader).addComponent(PillarOfFortuneWatingRoom);
    }

    init() {
        const players = this.context.players.getAll().filter((p) => p.isValid);
        const maxPlayers = this.context.map.startPoints.length;
        const watingPoint = this.context.map.watingPoint;
        let i = 0;
        //初始化玩家重生点和位置s
        for (; i < maxPlayers && i < players.length; i++) {
            players[i].player?.setSpawnPoint({
                dimension: Dimensions.Overworld,
                ...watingPoint,
            });
            players[i].player?.teleport(watingPoint);
        }
        //删掉多余的
        for (; i < players.length; i++) {
            players[i].sendMessage("人数过多，你被踢出了幸运之柱");
            this.context.players.delete(players[i]);
        }
    }

    initPlayer() {
        this.context.players.forEach((p) => {
            p.clear();
            p.player.setGameMode(GameMode.Adventure);
            p.player.runCommand("effect @s clear");
        });
    }

    next() {
        this.transitionTo(PillarOfFortuneWatingState);
    }

    end() {
        this.engine.stopGame();
    }
}
